﻿namespace SpikingVisualisationRLib

open RProvider
open RProvider.RInterop
open RProvider.``base``
open RProvider.graphics
open SpikingAnalyticsLib.ResponseFingerPrint    // for FrameProfile

[<AbstractClass; Sealed>]
type ResponseProfileVisualisation () =

    static let ShowHistogram (allMaps:Map<int, Map<int, int>>) row maxX maxY =

        let countData =
            allMaps.[row]
            |> Map.toSeq
            |> Seq.map (fun (time, count) -> count)

        let x = Array.init maxX (fun index -> index)

        namedParams [
            "height", box countData;
            "xlab", box "Time (msec)";
            "ylab", box "Count";
            "ylim", box [ 0; maxY; ];
            "names.arg", box x;
        ]
        |> R.barplot |> ignore

        // add a bounding box
        namedParams [
            "bty", box "o";     // full bounding box i.e. all sides
        ]
        |> R.box |> ignore

    /// Show selected response histograms from the specified FrameProfile
    static member ShowReponseProfileHistograms(profile:FrameProfile, selectedKeys:int list) =

        let maxX = profile.FrameSize;

        let maxY =
            let histograms = profile.ResponseHistograms
            selectedKeys
            |> Seq.map (fun key ->
                    let _, maxCount =
                        histograms.[key]
                        |> Map.toSeq
                        |> Seq.maxBy (fun (time, count) -> count)
                    maxCount
                )
            |> Seq.max

        // set the margins and number of rows
        namedParams [
            "mar", box [ 2; 5; 1; 1; ];             // bottom, left, top, right
            "mfrow", box [selectedKeys.Length; 1];
        ]
        |> R.par |> ignore

        for key in selectedKeys do
            ShowHistogram profile.ResponseHistograms key maxX maxY
